﻿using Microsoft.Extensions.Logging;
using Puppy.Scheduler.Common;
using Puppy.Scheduler.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Puppy.Scheduler.Processors
{
    /// <summary>
    /// Map 处理器，允许开发者自定义拆分任务进行分布式执行
    /// </summary>
    public abstract class MapProcessor : ProcessorBase
    {
        /// <summary>
        /// 推荐批次大小，默认为200
        /// </summary>
        protected virtual int DefaultBatchSize { get; set; } = 200;

        /// <summary>
        /// 分发子任务
        /// </summary>
        /// <param name="taskList">子任务，再次执行时可通过 TaskContext#getSubTask 获取</param>
        /// <param name="taskName">子任务名称，即子任务处理器中 TaskContext#getTaskName 获取到的值</param>
        /// <returns>map结果</returns>
        public Task<ProcessResult> Map(List<object> taskList, string taskName)
        {
            if (taskList.IsNullOrEmpty())
                return Task.FromResult(new ProcessResult(false, "taskList can't be null"));

            if (taskList.Count > DefaultBatchSize)
                Logger.LogWarning($"map task size greater than default batch size {DefaultBatchSize}, network maybe overload... please try to split the tasks.");

            var task = ThreadLocalStore.GetTask();

            var req = new ProcessorMapTaskRequest(task, taskList, taskName);

            // todo: 发送请求下发任务
            return Task.FromResult(new ProcessResult(true, "Map Success"));
        }

        public static bool IsRootTask()
        {
            var task = ThreadLocalStore.GetTask();
            return task.TaskName == WorkerConsts.RootTaskName;
        }
    }
}
